<script setup>
import axios from 'axios'
import Edit from './components/Edit.vue'
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// TODO: 列表渲染
let list = ref([])
let getList = async () => {
  let { data } = await axios.get('/list')
  list.value = data
}
// 发送请求
onMounted(() => getList())

// TODO: 删除功能
const del = async (id) => {
  // 1. 弹出确认框
  let res = await ElMessageBox.confirm(
    '您确定删除吗?',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  ).catch(err => err)
  // 2. 如果点击的是取消
  if (res === 'cancel') return ElMessage('您取消了删除操作!');
  // 3.如果点击的是确定
  let { data } = await axios.delete(`/del/${id}`)
  // 4. 如果删除成功!
  if (data.success)  ElMessage.success('删除成功!');
  getList()// 更新数据
}
// TODO: 编辑功能
let editRef = ref(null)

</script>
<template>
  <div class="app">
    <el-table :data="list">
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="姓名" prop="name" width="150"></el-table-column>
      <el-table-column label="籍贯" prop="place"></el-table-column>
      <el-table-column label="操作" width="150">
        <!--  #default="{ row }" -->
        <template #default="{ row }">
          <el-button type="primary" link @click="editRef.open(row)">编辑</el-button>
          <el-button type="danger" link @click="del(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <Edit ref="editRef" />
</template>

<style scoped>
.app {
  width: 980px;
  margin: 100px auto 0;
}
</style>
